//
//  MapNavgationController.m
//  i5db
//
//  Created by iMuse on 15-5-27.
//  Copyright (c) 2015年 mySelf. All rights reserved.
//

#import "MapNavgationController.h"
#import "BMKCustomPointAnnotation.h"
#import "CustomPaopaoView.h"
#import <BaiduMapAPI/BMapKit.h>
#import "AppCenter.h"
#import "MapSheetView.h"
#import "HUD.h"
@interface MapNavgationController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,CustomPaopaoViewDelegate,MapSheetViewDeleagte>
{
    BMKMapView* _mapView;
    BMKLocationService * _locService;
    BMKPolyline* polyline;
    BMKGeoCodeSearch* _geocodesearch;
}

@property (nonatomic,assign) double currentLatitude;
@property(nonatomic,assign) double  currentLongitude;


@end

@implementation MapNavgationController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       self.title = @"位置";
    }
    return self;
}

-(void)initNavigationBar
{
    [super initNavigationBar];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavigationBar];
  
    [self initView];
   
}

-(void) initView
{
  CLLocationCoordinate2D pt = (CLLocationCoordinate2D){39.872999,116.496648};
  
   _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
   
    _mapView.zoomLevel = 17;
    _mapView.centerCoordinate = pt;
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    
    
    UIButton * buttonLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonLocation addTarget:self action:@selector(mapCenterButton:) forControlEvents:UIControlEventTouchUpInside];
    buttonLocation.frame = CGRectMake(_mapView.frame.size.width-70, _mapView.frame.size.height-60, 40, 40);
    
    
    [buttonLocation setBackgroundImage:[UIImage imageNamed:@"wl_map_icon_position"] forState:UIControlStateNormal];
    
    [self.view addSubview:buttonLocation];
    
   BMKPointAnnotation*  annotation = [[BMKPointAnnotation alloc]init];
    annotation.coordinate = pt;
   annotation.title = @"欢乐谷";
  [_mapView addAnnotation:annotation];
    
   [_mapView selectAnnotation:annotation animated:YES];
    
    
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    _mapView.showMapScaleBar = YES;
    _mapView.mapScaleBarPosition = CGPointMake(20, _mapView.frame.size.height-60);
  
    
   
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[BMKPolyline class]]){
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.strokeColor = [[UIColor purpleColor] colorWithAlphaComponent:1];
        polylineView.lineWidth = 2.0;
        
        return polylineView;
    }
    return nil;
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)thannotation
{
    
    BMKCustomPointAnnotation * annotation = (BMKCustomPointAnnotation*)thannotation;
    
    if ([thannotation isKindOfClass:[BMKPointAnnotation class]]) {
        
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
      
        CustomPaopaoView * popoView = [[CustomPaopaoView alloc] init:annotation.title];
      
        popoView.delegate  = self;
        
        BMKActionPaopaoView * view = [[BMKActionPaopaoView alloc] initWithCustomView:popoView];
        newAnnotationView.calloutOffset = CGPointMake(0, -10);
        
      
        newAnnotationView.image = [UIImage imageNamed:@"anjuke_icon_itis_position"];
        newAnnotationView.paopaoView = view;
        newAnnotationView.canShowCallout = YES;
        
       
      
        return newAnnotationView;
    }
    
    return nil;
}

-(void)selectMap
{
    NSString * string = @"";
    if (polyline !=nil)
    {
       string = @"隐藏路线";
    }else
    {
        string = @"显示路线";
    }
    
    NSMutableArray * mapArray = [[NSMutableArray alloc] init];
    for (NSString* str in [AppCenter checkMaps])
    {
        [mapArray addObject:str];
    }
    [mapArray addObject:string];
    
    [MapSheetView showMapsArray:mapArray delegate:self];
}
-(void)mapSheetButton:(UIButton *)button
{
    
    NSString * title = button.titleLabel.text;
    if ([title isEqualToString:@"显示路线"])
    {
        
        [button setTitle:@"隐藏路线" forState:UIControlStateNormal];
        CLLocationCoordinate2D coors[2] = {0};
        coors[0].latitude = self.currentLatitude;
        coors[0].longitude = self.currentLongitude;
        coors[1].latitude = 39.872999;
        coors[1].longitude = 116.496648;
        
        polyline = [BMKPolyline polylineWithCoordinates:coors count:2];
        [_mapView addOverlay:polyline];
        
    }else if ([title isEqualToString:@"隐藏路线"])
    {
        [button setTitle:@"显示路线" forState:UIControlStateNormal];
        if (polyline!=nil)
        {
            [_mapView removeOverlay:polyline];
        }
    }else if ([title isEqualToString:@"百度地图"])
    {
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:终点&mode=driving",self.currentLatitude, self.currentLongitude,39.872999,116.496648] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
        
    }else if ([title isEqualToString:@"苹果地图"])
    {
        /*NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"iosamap://navi?sourceApplication=applicationName&backScheme=applicationScheme&poiname=fangheng&poiid=BGVIS&lat=36.547901&lon=104.258354&dev=1&style=2",self.addressStr,self.naviCoordsGd.latitude,self.naviCoordsGd.longitude]];
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];*/
    }
}





-(void)mapCenterButton:(UIButton*) button
{
     CLLocationCoordinate2D pt = (CLLocationCoordinate2D){39.872999,116.496648};
    
     _mapView.centerCoordinate = pt;
    
}

- (void)willStartLocatingUser
{
   
    [HUD showUIBlockingIndicatorWithText:@"正在定位"];
}
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.currentLatitude  = userLocation.location.coordinate.latitude;
    self.currentLongitude = userLocation.location.coordinate.longitude;
    [HUD hideUIBlockingIndicator];

    
  
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    [HUD showUIBlockingIndicatorWithText:@"定位失败" withTimeout:2];
}

- (void)viewWillAppear:(BOOL)animated {
    
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    _mapView = nil;
    _mapView.delegate = nil;
    _locService = nil;
    _geocodesearch.delegate = nil;
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    
    [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}


@end
